import axios from 'axios'
import { Toast } from 'vant'

import { getToken } from '@/utils/token'

import router from '@/router'
const request = axios.create({
  baseURL: 'http://interview-api-t.itheima.net/'
})

// 请求拦截

request.interceptors.request.use(
  config => {
    config.headers.Authorization = ` Bearer ${getToken()}`
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// 响应拦截
request.interceptors.response.use(
  response => {
    return response.data
  },
  err => {
    if (err.response.status === 401) {
      Toast('登录状态失效,重新登录')
      router.push('/login')
    } else {
      Toast.fail(err.response.data.message)
    }
    return Promise.reject(err)
  }
)
export default request
